package cn.kgc.education.controller;

import cn.kgc.education.entity.Teacher;
import cn.kgc.education.response.ResponseResult;
import cn.kgc.education.service.TeacherService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/9/9
 * @description 处理教师相关请求
 */
@RestController
@RequestMapping("teacher")
public class TeacherController {


    @Resource
    private TeacherService teacherService;

    //  教师数据分页接口
    @RequestMapping("page")
    public ResponseResult teacherPage(Integer page, Integer limit, String name, Double salary) {

        // 分页对象
        Page<Teacher> teacherPage = new Page<>(page, limit);

        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        //  where  name like  '%a%'  and  salary = ?
        teacherQueryWrapper.like(StringUtils.isNotBlank(name), "name", name)
                .eq(ObjectUtils.isNotNull(salary), "salary", salary);

        teacherService.page(teacherPage, teacherQueryWrapper);


        List<Teacher> records = teacherPage.getRecords();
        long total = teacherPage.getTotal();

        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(0);
        responseResult.setData(records);
        responseResult.setCount(total);


        return responseResult;
    }


    // 删除教师信息
    @RequestMapping("delete")
    public ResponseResult deleteTeacher(String ids) {

        // 将字符串id  处理成集合
        String[] batchIds = ids.split(",");
        ArrayList<Integer> intIds = new ArrayList<>();
        for (String batchId : batchIds) {
            intIds.add(Integer.valueOf(batchId));
        }


        teacherService.removeBatchByIds(intIds);

        ResponseResult responseResult = new ResponseResult();

        responseResult.setCode(0);
        responseResult.setMsg("删除成功");


        return responseResult;
    }


    // 编辑 / 添加教师信息
    @RequestMapping("addOrUpdate")
    public ResponseResult addOrUpdateTeacher(Teacher teacher) {

        teacherService.saveOrUpdate(teacher);

        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(0);
        responseResult.setMsg("操作成功");

        return  responseResult;
    }

}
